package com.emex.app.stuff.cashbox;

import com.emex.app.shared.data.Cashbox;
import com.emex.app.shared.data.Cost;
import com.emex.app.shared.data.OrderPayment;
import com.emex.app.shared.data.Profit;
import com.emex.app.shared.data.enums.PayMethod;
import com.emex.app.stuff.constant.ReportName;
import com.emex.app.stuff.gui.CostDialog;
import com.emex.app.stuff.gui.ProfitDialog;
import com.emex.app.stuff.provider.CostDataProvider;
import com.emex.app.stuff.provider.OrderDataProvider;
import com.emex.app.stuff.provider.ProfitDataProvider;
import com.emex.app.stuff.utils.DateUtils;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.UIUtils;
import java.awt.image.BufferedImage;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.imageio.ImageIO;
import net.sf.jasperreports.engine.JasperPrint;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Exceptions;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.emex.app.stuff.cashbox//CashBox//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "CashBoxTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.emex.app.stuff.cashbox.CashBoxTopComponent")
@ActionReference(path = "Menu/Касса" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_CashBoxAction",
        preferredID = "CashBoxTopComponent"
)
@Messages({
    "CTL_CashBoxAction=Касса",
    "CTL_CashBoxTopComponent=Касса",
    "HINT_CashBoxTopComponent=Касса"
})
public final class CashBoxTopComponent extends TopComponent {

    private Cashbox cashbox;

    private Double cash = 0.0;

    private Double bank = 0.0;

    private Double qiwi = 0.0;

    public CashBoxTopComponent() {
        initComponents();
        setName(Bundle.CTL_CashBoxTopComponent());
        setToolTipText(Bundle.HINT_CashBoxTopComponent());
        customInit();
    }

    private void customInit() {
        cashbox = OrderDataProvider.getInstance().getCashBox();
        if (null != cashbox) {
            controlsStateChanged(false);
            cashTextField.setText(cashbox.getCashBalance().toString());
            bankTextField.setText(cashbox.getBankBalance().toString());
            qiwiTextField.setText(cashbox.getQiwiBalance().toString());
            printCashBoxOrder.setEnabled(true);
        } else {
            controlsStateChanged(true);
            printCashBoxOrder.setEnabled(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cashBoxPanel = new javax.swing.JPanel();
        cashTextField = new javax.swing.JTextField();
        bankTextField = new javax.swing.JTextField();
        qiwiTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        saveStartParametrsButton = new javax.swing.JButton();
        printCashBoxOrder = new javax.swing.JButton();
        addProfitButton = new javax.swing.JButton();
        addCostButton = new javax.swing.JButton();

        cashBoxPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.cashBoxPanel.border.title"))); // NOI18N

        cashTextField.setText(org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.cashTextField.text")); // NOI18N
        cashTextField.setEnabled(false);

        bankTextField.setText(org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.bankTextField.text")); // NOI18N
        bankTextField.setEnabled(false);

        qiwiTextField.setText(org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.qiwiTextField.text")); // NOI18N
        qiwiTextField.setEnabled(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(saveStartParametrsButton, org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.saveStartParametrsButton.text")); // NOI18N
        saveStartParametrsButton.setEnabled(false);
        saveStartParametrsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveStartParametrsButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout cashBoxPanelLayout = new javax.swing.GroupLayout(cashBoxPanel);
        cashBoxPanel.setLayout(cashBoxPanelLayout);
        cashBoxPanelLayout.setHorizontalGroup(
            cashBoxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(cashBoxPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(cashBoxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cashTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(60, 60, 60)
                .addGroup(cashBoxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bankTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(60, 60, 60)
                .addGroup(cashBoxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(cashBoxPanelLayout.createSequentialGroup()
                        .addComponent(qiwiTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(saveStartParametrsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        cashBoxPanelLayout.setVerticalGroup(
            cashBoxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(cashBoxPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(cashBoxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(cashBoxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cashTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bankTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(qiwiTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveStartParametrsButton))
                .addContainerGap())
        );

        org.openide.awt.Mnemonics.setLocalizedText(printCashBoxOrder, org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.printCashBoxOrder.text")); // NOI18N
        printCashBoxOrder.setEnabled(false);
        printCashBoxOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printCashBoxOrderActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(addProfitButton, org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.addProfitButton.text")); // NOI18N
        addProfitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addProfitButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(addCostButton, org.openide.util.NbBundle.getMessage(CashBoxTopComponent.class, "CashBoxTopComponent.addCostButton.text")); // NOI18N
        addCostButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addCostButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cashBoxPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(printCashBoxOrder)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(addProfitButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(addCostButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cashBoxPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addProfitButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addCostButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(printCashBoxOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(94, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void saveStartParametrsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveStartParametrsButtonActionPerformed
        if (null == cashTextField.getText() || cashTextField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Введите начальную сумму наличных в кассе");
            return;
        }
        if (null == bankTextField.getText() || bankTextField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Введите начальную сумму денег в банке");
            return;
        }
        if (null == qiwiTextField.getText() || qiwiTextField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Введите начальную сумму в QIWI кошельке");
            return;
        }

        cashbox = new Cashbox();
        cashbox.setCashBalance(Double.valueOf(cashTextField.getText()));
        cashbox.setBankBalance(Double.valueOf(bankTextField.getText()));
        cashbox.setQiwiBalance(Double.valueOf(qiwiTextField.getText()));
        cashbox.setDate(new Date());
        cashbox = OrderDataProvider.getInstance().insertCashbox(cashbox);
        controlsStateChanged(false);
        printCashBoxOrder.setEnabled(true);
    }//GEN-LAST:event_saveStartParametrsButtonActionPerformed

    private void printCashBoxOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printCashBoxOrderActionPerformed
        if (null != cashbox) {
            try {
                calculateCashbox();
                HashMap parameters = new HashMap();
                boolean isAvtozavod = true;
                String template;
                if (isAvtozavod) {
                    BufferedImage logo_avtoz = ImageIO.read(getClass().getClassLoader().getResource("logo_avtoz.jpg"));
                    BufferedImage logo = ImageIO.read(getClass().getClassLoader().getResource("body.jpg"));
                    parameters.put("logo", logo_avtoz);
                    parameters.put("logo_vizit", logo);
                    template = ReportName.CASHBOX_REPORT_AVTOZAVOD;
                } else {
                    BufferedImage image = ImageIO.read(getClass().getClassLoader().getResource("emexLogo.jpg"));
                    parameters.put("logo", image);
                    template = ReportName.CASHBOX_REPORT;
                }
                parameters.put("cash", round(cash, 2) + " р.");
                parameters.put("bank", round(bank, 2) + " р.");
                parameters.put("qiwi", round(qiwi, 2) + " р.");
                String minutes = "";
                if (Calendar.getInstance().get(Calendar.MINUTE) > 9) {
                    minutes += Calendar.getInstance().get(Calendar.MINUTE);
                } else {
                    minutes += "0" + Calendar.getInstance().get(Calendar.MINUTE);
                }
                String curDateTime = DateUtils.getExtendedFormattedString(new Date())
                        + " " + Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + minutes;
                parameters.put("cur_date_time", curDateTime);
                JasperPrint jp = ReportGenerator.getInstance().generateReport(parameters, template);
                ReportGenerator.getInstance().showReport(jp);

            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
                UIUtils.showErrorMessage("Произошли ошибки при печати кассового ордера");
            }
        }
    }//GEN-LAST:event_printCashBoxOrderActionPerformed

    private void addProfitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addProfitButtonActionPerformed
        ProfitDialog dialog = new ProfitDialog(WindowManager.getDefault().getMainWindow(), true);
        dialog.setDate(new Date());
        dialog.setLocationRelativeTo(null);
        dialog.setTitle("Добавить новый доход");
        dialog.setVisible(true);
    }//GEN-LAST:event_addProfitButtonActionPerformed

    private void addCostButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addCostButtonActionPerformed
        CostDialog dialog = new CostDialog(WindowManager.getDefault().getMainWindow(), true);
        dialog.setDate(new Date());
        dialog.setLocationRelativeTo(null);
        dialog.setTitle("Добавить новый расход");
        dialog.setVisible(true);
    }//GEN-LAST:event_addCostButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addCostButton;
    private javax.swing.JButton addProfitButton;
    private javax.swing.JTextField bankTextField;
    private javax.swing.JPanel cashBoxPanel;
    private javax.swing.JTextField cashTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton printCashBoxOrder;
    private javax.swing.JTextField qiwiTextField;
    private javax.swing.JButton saveStartParametrsButton;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    private void controlsStateChanged(boolean state) {
        cashTextField.setEnabled(state);
        bankTextField.setEnabled(state);
        qiwiTextField.setEnabled(state);
        saveStartParametrsButton.setEnabled(state);
    }

    private void calculateCashbox() {
        if (null != cashbox) {
            cash = cashbox.getCashBalance();
            bank = cashbox.getBankBalance();
            qiwi = cashbox.getQiwiBalance();
            // 1. Get all payments from given date and calculate them
            List<OrderPayment> orderPayments
                    = OrderDataProvider.getInstance().
                    getOrderPaymentsByDateEqualOrGrater(cashbox.getDate());
            if (null != orderPayments && !orderPayments.isEmpty()) {
                for (OrderPayment op : orderPayments) {
                    PayMethod payMethod = PayMethod.valueOf(op.getPayMethod());
                    switch (payMethod) {
                        case CARD:
                            bank += op.getSumma();
                            break;
                        case CASH:
                            cash += op.getSumma();
                            break;
                        case KARTA:
                            Double comisson = (op.getSumma() / 100) * 1.8;
                            Double inBank = op.getSumma() - comisson;
                            bank += inBank;
                            break;
                        case QIWI:
                            qiwi += op.getSumma();
                            break;
                    }
                }
            }
            // 2. Get all profits from given date
            List<Profit> profits = ProfitDataProvider.getInstance().
                    getAllProfitsByDateEqualOrGraterThan(cashbox.getDate());
            if (null != profits && !profits.isEmpty()) {
                for (Profit profit : profits) {
                    PayMethod payMethod = PayMethod.valueOf(profit.getPayMethod());
                    switch (payMethod) {
                        case CARD:
                            bank += profit.getSumma();
                            break;
                        case CASH:
                            cash += profit.getSumma();
                            break;
                        case KARTA:
                            Double comisson = (profit.getSumma() / 100) * 1.8;
                            Double inBank = profit.getSumma() - comisson;
                            bank += inBank;
                            break;
                        case QIWI:
                            qiwi += profit.getSumma();
                            break;
                    }
                }
            }
            // 3. Get all costs from given date
            List<Cost> costs = CostDataProvider.getInstance().
                    getAllCostsByDateEqualOrGrater(cashbox.getDate());
            if (null != costs && !costs.isEmpty()) {
                for (Cost cost : costs) {
                    PayMethod payMethod = PayMethod.valueOf(cost.getPayMethod());
                    switch (payMethod) {
                        case CARD:
                            bank -= cost.getSumma();
                            break;
                        case CASH:
                            cash -= cost.getSumma();
                            break;
                        case KARTA:
                            bank -= cost.getSumma();
                            break;
                        case QIWI:
                            qiwi -= cost.getSumma();
                            break;
                    }
                }
            }
        }

    }

    public double round(double value, int places) {
        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }
}
